package projectx.db;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.log4j.Logger;

import projectx.core.base.ProjectXContext;
import projectx.core.base.ProjectXSystemException;

public final class ProjectXDataSource {

	// --------------------------------------------------------------------------
	// S T A T I C M E M B E R S
	//
	// --------------------------------------------------------------------------
	private static final Logger _log = Logger.getLogger(ProjectXDataSource.class
			.getName());

	private static boolean _initialized;
	private static String _jndiName;
	private static DataSource _dataSource;

	// --------------------------------------------------------------------------
	// S T A T I C M E T H O D S
	//
	// --------------------------------------------------------------------------

	public static void initialize(String jndiName)
			throws ProjectXSystemException {

		if (!_initialized) {

			synchronized (ProjectXDataSource.class) {

				if (!_initialized) {

					_jndiName = jndiName;

					_log.info("Initialize using [" + _jndiName + "]...");

					_dataSource = (DataSource) ProjectXContext.lookup(_jndiName);

					_log.info("Initialized successfully");

					_initialized = true;
				}
			}
		}
	}

	public static Connection getConnection() throws SQLException {

		return _dataSource.getConnection();
	}

	public static boolean isInitialized() {
		return _initialized;
	}

	// --------------------------------------------------------------------------
	// C O N S T R U C T O R S
	//
	// --------------------------------------------------------------------------
	private ProjectXDataSource() {
	}
}
